AWS_PROFILE = phase2-sso
TF_DIR      = infra/aws
REGION      = us-east-1
EKSCTL_YAML = infra/eksctl/eksctl-cluster.yaml
CLUSTER     = dev

# --- 新增：脚本路径与开关 ---
SCRIPTS_DIR           ?= scripts
LIFECYCLE_DIR         ?= $(SCRIPTS_DIR)/lifecycle
PRE_TEARDOWN          ?= $(LIFECYCLE_DIR)/pre-teardown.sh
POST_TEARDOWN         ?= $(LIFECYCLE_DIR)/post-teardown.sh
POST_RECREATE         ?= $(LIFECYCLE_DIR)/post-recreate.sh
SCALE_NODEGROUP_ZERO  ?= $(LIFECYCLE_DIR)/scale-nodegroup-zero.sh
DRY_RUN               ?= false          # true 仅打印将执行的操作
UNINSTALL_METRICS     ?= true           # pre-teardown 默认卸载 metrics-server
UNINSTALL_ADOT        ?= true           # pre-teardown 默认卸载 ADOT Collector
UNINSTALL_GRAFANA     ?= true           # pre-teardown 默认卸载 Grafana
ENABLE_CHAOS_MESH     ?= false          # post-recreate 可选安装 Chaos Mesh
UNINSTALL_CHAOS_MESH  ?= true           # pre-teardown 默认卸载 Chaos Mesh

# --- 日志目录与时间戳 ---
LOG_DIR ?= scripts/logs
NOW := $(shell date +%Y%m%d%H%M%S)

.PHONY: check check-auto preflight aws-login init plan start post-recreate start-all \
        scale-zero stop pre-teardown post-teardown stop-all destroy-all logs clean-all \
        clean-logs update-diagrams lint

## 🛠️ 环境检查（工具版本、路径等）
check:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "🔎 检查 CLI 工具链状态..." | tee $$LOG_FILE; \
		bash scripts/check-tools.sh 2>&1 | tee -a $$LOG_FILE

## 自动安装全部缺失工具
check-auto:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "🔧 自动安装缺失工具..." | tee $$LOG_FILE; \
		bash scripts/check-tools.sh --auto 2>&1 | tee -a $$LOG_FILE

## 🧪 预检 AWS Service Quota 等限制
preflight:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "🧪 预检 AWS Service Quota 等限制" | tee $$LOG_FILE; \
		bash scripts/preflight.sh 2>&1 | tee -a $$LOG_FILE

## 🔑 登录 AWS SSO
aws-login:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "🔑 正在登录 AWS SSO..." | tee $$LOG_FILE; \
		aws sso login --profile $(AWS_PROFILE) 2>&1 | tee -a $$LOG_FILE

## 🧰 初始化 Terraform
init:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "Initializing Terraform..." | tee $$LOG_FILE; \
		terraform -chdir=$(TF_DIR) init -reconfigure 2>&1 | tee -a $$LOG_FILE

## ▶ 显示当前计划（Terraform 管理 NAT / EKS 控制面）
plan:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "Planning Terraform changes..." | tee $$LOG_FILE; \
		terraform -chdir=$(TF_DIR) plan \
			-var="region=$(REGION)" \
			-var="create_nat=true" \
			-var="create_eks=true" \
			2>&1 | tee -a $$LOG_FILE

## ☀ 通过 Terraform 启动 NAT 网关与 EKS 控制面
start:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "Applying Terraform changes to start NAT and EKS..." | tee $$LOG_FILE; \
		terraform -chdir=$(TF_DIR) apply -auto-approve -input=false \
			-var="region=$(REGION)" \
			-var="create_nat=true" \
			-var="create_eks=true" \
			2>&1 | tee -a $$LOG_FILE

## 📨 部署后续：刷新 kubeconfig、安装 ALB Controller/Autoscaler/metrics-server/ADOT/Grafana、
##     （可选）Chaos Mesh，并绑定 Spot 中断通知
post-recreate:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "Running post-recreate tasks..." | tee $$LOG_FILE; \
		REGION=$(REGION) PROFILE=$(AWS_PROFILE) CLUSTER_NAME=$(CLUSTER) \
			ENABLE_CHAOS_MESH=$(ENABLE_CHAOS_MESH) \
			bash $(POST_RECREATE) 2>&1 | tee -a $$LOG_FILE

## 🚀 一键执行 Terraform 部署并运行 post-recreate 脚本
start-all: start post-recreate
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "start-all completed" | tee $$LOG_FILE

## 🌙 缩容所有 EKS 节点组至 0
scale-zero:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "🌙 Scaling down all EKS node groups to zero..." | tee $$LOG_FILE; \
		bash $(SCALE_NODEGROUP_ZERO) 2>&1 | tee -a $$LOG_FILE

## 🌙 销毁 NAT 网关和 EKS 控制面（先缩容节点组）
stop: scale-zero
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "Stopping all resources (NAT and EKS control plane)..." | tee $$LOG_FILE; \
		terraform -chdir=$(TF_DIR) apply -auto-approve -input=false \
			-var="region=$(REGION)" \
			-var="create_nat=false" \
			-var="create_eks=false" \
			2>&1 | tee -a $$LOG_FILE

## 🧼 在销毁前优雅释放：删除 ALB Ingress、等待回收 ALB/TG，卸载 ALB Controller，
##     并可选卸载 metrics-server/ADOT/Grafana/Chaos Mesh
pre-teardown:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "🧹 [pre-teardown] 删除 Ingress & 卸载 ALB Controller (+ metrics-server)" | tee $$LOG_FILE; \
		REGION=$(REGION) PROFILE=$(AWS_PROFILE) CLUSTER_NAME=$(CLUSTER) \
			UNINSTALL_METRICS_SERVER=$(UNINSTALL_METRICS) \
			UNINSTALL_ADOT_COLLECTOR=$(UNINSTALL_ADOT) \
			UNINSTALL_GRAFANA=$(UNINSTALL_GRAFANA) \
			UNINSTALL_CHAOS_MESH=$(UNINSTALL_CHAOS_MESH) \
			bash $(PRE_TEARDOWN) 2>&1 | tee -a $$LOG_FILE

## 🛠️ 清理残留 CloudWatch 日志组，强删与集群相关的 ALB/TargetGroup/安全组，
##     并验证 NAT/EKS/ASG 通知已移除（支持 DRY_RUN）
post-teardown:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "Running post-teardown tasks..." | tee $$LOG_FILE; \
		REGION=$(REGION) PROFILE=$(AWS_PROFILE) CLUSTER_NAME=$(CLUSTER) \
			DRY_RUN=$(DRY_RUN) \
			bash $(POST_TEARDOWN) 2>&1 | tee -a $$LOG_FILE

## 🧹 销毁集群后清理残留（pre-teardown → stop → post-teardown）
stop-all: pre-teardown stop post-teardown
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "stop-all completed" | tee $$LOG_FILE

## 💣 一键彻底销毁所有资源（包含 pre-/post-teardown）
destroy-all: pre-teardown stop
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		{ echo "🔥 Destroying all Terraform-managed resources..."; \
		terraform -chdir=$(TF_DIR) destroy -auto-approve -input=false \
			-var="region=$(REGION)"; \
		echo "Running post-teardown cleanup..."; \
		REGION=$(REGION) PROFILE=$(AWS_PROFILE) CLUSTER_NAME=$(CLUSTER) \
			DRY_RUN=$(DRY_RUN) \
			bash $(POST_TEARDOWN); } 2>&1 | tee $$LOG_FILE

## 📜 查看最近的日志
logs:
	@mkdir -p $(LOG_DIR)
	@ls -lt $(LOG_DIR) | head -n 5
	@echo "..."
	@echo ""
	@echo "--- 最近日志内容（最近 3 个日志文件的 末尾 10 行） ---"
	@echo ""
	@ls -1t $(LOG_DIR)/*.log 2>/dev/null | head -n 3 | while read f; do \
		basename "$$f"; \
		echo "==================================================="; \
		tail -n 10 "$$f"; \
		echo "==================================================="; \
		echo ""; \
		done

# 🧹 清理临时文件、日志与 Terraform 缓存
clean-all:
	@mkdir -p $(LOG_DIR)
	@echo "🧹 Cleaning caches and logs..."
	@rm -f scripts/.last-asg-bound
	@rm -f $(LOG_DIR)/*.log 2>/dev/null || true
	@rm -f scripts/*.tmp scripts/*.bak 2>/dev/null || true
	@rm -f plan.out *.tfplan 2>/dev/null || true
	@rm -rf $(TF_DIR)/.terraform 2>/dev/null || true
	@rm -rf $(TF_DIR)/modules/*/.terraform 2>/dev/null || true
	@rm -rf $(TF_DIR)/modules/*/.terraform.lock.hcl 2>/dev/null || true
	@echo "🧹 清理完成：临时文件和日志已删除"

clean-logs:
	@mkdir -p $(LOG_DIR)
	@echo "🧹 Cleaning all logs..."
	@rm -f $(LOG_DIR)/*.log 2>/dev/null || true
	@echo "🧹 日志清理完成"

# 📊 更新架构图
update-diagrams:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "📊 更新架构图..." | tee $$LOG_FILE; \
		bash scripts/update-diagrams.sh 2>&1 | tee -a $$LOG_FILE

## 📦 运行 pre-commit 检查（terraform fmt / tflint / yamllint 等）
lint:
	@mkdir -p $(LOG_DIR)
	@LOG_FILE=$(LOG_DIR)/$@-$(NOW).log; \
		echo "🔍 Running pre-commit checks..." | tee $$LOG_FILE; \
		pre-commit run --all-files --verbose --show-diff-on-failure 2>&1 | tee -a $$LOG_FILE
